package com.ruoyi.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.user.Result;
import com.ruoyi.common.core.exception.user.StatusCode;
import com.ruoyi.common.core.utils.JwtUtil;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.user.entity.User;
import com.ruoyi.user.service.UserService;
import com.ruoyi.user.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 14571
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2023-03-22 18:30:27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{

    @Resource
    private StringRedisTemplate redis;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public Result register(User user) {
        String code = redis.opsForValue().get(user.getMobile());
        if (!code.equals(user.getCode())){
            return Result.error(StatusCode.ERROR,"验证码错误");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User uu = this.getOne(userQueryWrapper);
        if (uu!=null){
            return Result.error(StatusCode.ERROR,"用户名已存在");
        }
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        try {
            user.setRoleId(3);
            this.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(StatusCode.ERROR, "注册失败");
        }
        return Result.success();
    }

    @Override
    public Result sendCode(String mobile) {
        String code = redis.opsForValue().get(mobile);
        if (StringUtils.isNotBlank(code)){
            return Result.error(StatusCode.ERROR, "验证码未过期");
        }
        code = RandomUtil.randomNumbers(6);
        //DuanxinUtils.sendDuanxin(mobile, code);
        redis.opsForValue().set(mobile,code,60, TimeUnit.SECONDS);
        return Result.success();
    }

    @Override
    public Result login(User user, HttpSession session) throws UnsupportedEncodingException {
        String code = redis.opsForValue().get(user.getMobile());
        if (!code.equals(user.getCode())){
            return Result.error(StatusCode.ERROR,"验证码错误");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User uu = this.getOne(userQueryWrapper);
        if (uu==null){
            return Result.error(StatusCode.LOGINERROR,"用户名或密码错误");
        }
        if (!bCryptPasswordEncoder.matches( user.getPassword() , uu.getPassword())){
            return Result.error(StatusCode.LOGINERROR, "用户名或密码错误");
        }
        String token = JwtUtil.sign(uu.getId() + "", uu.getUsername(), "zhuay");
        redis.opsForValue().set(token,"",3, TimeUnit.MINUTES);
        session.setAttribute("userId", uu.getId());
        session.setAttribute("userName", uu.getUsername());
        return Result.success(token);
    }
}